﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FrameworkLib.Facades;
using FrameworkLib.Configurations.FormsConfiguration.BL;
using FrameworkLib.Configurations.FormsConfiguration.DAL;

namespace FrameworkLib.Configurations.FormsConfiguration.Facade
{
    [Serializable]
    public class FormsConfigurationFacade : FacadeBase<FormsConfigurationEntities>
    {
        FormsConfigurationEntities context = null;
        private string m_errorOccurred = string.Empty;

        public string ErrorOccurred
        {
            get { return m_errorOccurred; }
            set { m_errorOccurred = value; }
        }

        public FormsConfigurationFacade()
        {
            context = this.GetContext();
        }

        public FormsConfigurationFacade(string connectionString)
        {
            context = this.GetContext(connectionString);
        }

        public static FormConfiguration CreateFormConfiguration(string formName)
        {
            FormConfiguration retValue = new FormConfiguration();
            retValue.FormName = formName;

            DAL.FormsList fconf = new DAL.FormsList();
            fconf.FormName = formName;

            FormsConfigurationEntities context = new FormsConfigurationEntities();
            context.FormsList.AddObject(fconf);
            context.SaveChanges();

            retValue.ID = fconf.IDForm;

            return retValue;
        }

        public bool Delete(short id)
        {
            bool retValue = false;

            var obj = from x in context.FormsList where x.IDForm == id select x;

            if (obj.Any())
            {
                context.FormsList.DeleteObject(obj.FirstOrDefault());

                context.SaveChanges();

                retValue = true;
            }

            //
            return retValue;
        }

        public List<FormConfiguration> GetForms()
        {
            List<FormConfiguration> retValue = null;

            var objs = from x in context.FormsList select new FormConfiguration { 
                ID = x.IDForm, 
                FormName = x.FormName.Trim(),
                RoleName = x.RoleName.Trim(),
                UserName = x.UserName.Trim()
            };

            if (objs.Any())
            {
                retValue = objs.ToList();
            }

            return retValue;
        }

        public FormConfiguration GetForm(string formName)
        {
            FormConfiguration retValue = null;

            var objs = from x in context.FormsList where x.FormName==formName select new FormConfiguration { ID = x.IDForm, FormName = x.FormName };

            if (objs.Any())
            {
                retValue = objs.FirstOrDefault();
            }

            return retValue;
        }

        public List<ColumnConfiguration> GetColumns(string formName)
        {
            List<ColumnConfiguration> retValue = null;

            var objs = from x in context.FormsList
                       join y in context.ColumnsConfiguration on x.IDForm equals y.IDForm
                       select new ColumnConfiguration
                       {
                           ID = y.IDColumn,
                           ColumnName = y.ColumnName,
                           IsVisible = y.IsVisible,
                           Owner = new FormConfiguration { ID = x.IDForm, FormName = x.FormName }
                       };

            if (objs.Any())
            {
                retValue = objs.ToList();
            }

            return retValue;
        }

        public bool SaveColumns(List<ColumnConfiguration> columns)
        {
            bool retValue = false;

            this.Transact(() =>
            {
                short id = columns[0].Owner.ID;
                var objs = from x in context.ColumnsConfiguration
                           where x.IDForm == id
                           select x;

                if (objs.Any())
                {
                    foreach (ColumnsConfiguration cc in objs)
                    {
                        context.ColumnsConfiguration.DeleteObject(cc);
                    }
                }

                foreach (ColumnConfiguration cc in columns)
                {
                    DAL.ColumnsConfiguration cconf = new DAL.ColumnsConfiguration();
                    cconf.ColumnName = cc.ColumnName;
                    cconf.IsVisible = cc.IsVisible;
                    cconf.IDForm = cc.Owner.ID;

                    context.ColumnsConfiguration.AddObject(cconf);
                }

                context.SaveChanges();

                retValue = true;

            });

            return retValue;
        }

        public bool SaveForm(List<FormConfiguration> forms)
        {
            bool retValue = false;

            this.Transact(() =>
            {
                foreach (FormConfiguration ff in forms)
                {
                    DAL.FormsList fconf = new DAL.FormsList();
                    fconf.FormName = ff.FormName;

                    context.FormsList.AddObject(fconf);
                }

                context.SaveChanges();

                retValue = true;
            });

            return retValue;
        }

        public bool SaveState(SavingConfigurationBag configuration, byte[] state)
        {
            bool retValue = false;

            try
            {
                DAL.FormsList fconf = null;

                IQueryable<FormsList> query = context.FormsList.Where(x => x.FormName == configuration.FormName);

                if (!string.IsNullOrWhiteSpace(configuration.RoleName))
                {
                    query = query.Where(x => x.RoleName == configuration.RoleName);
                }

                if (!string.IsNullOrWhiteSpace(configuration.UserName))
                {
                    query = query.Where(x => x.UserName == configuration.UserName);
                }

                //var obj = from x in context.FormsList
                //          where x.FormName == formName
                //          select x;

                //if (obj.Any())
                //{
                //    fconf = obj.FirstOrDefault();
                //}
                //else
                //{
                //    fconf = new DAL.FormsList();
                //    context.FormsList.AddObject(fconf);
                //}

                fconf = query.FirstOrDefault();
                if (fconf == null)
                {
                    fconf = new DAL.FormsList();
                    context.FormsList.AddObject(fconf);
                }

                fconf.FormName = configuration.FormName;
                fconf.RoleName = (string.IsNullOrWhiteSpace(configuration.RoleName) ? null : configuration.RoleName);
                fconf.UserName = (string.IsNullOrWhiteSpace(configuration.UserName) ? null : configuration.UserName);
                fconf.SerializedGridData = state;

                context.SaveChanges();

                retValue = true;
            }
            catch (Exception ex)
            {
                ErrorOccurred = ex.Message;
            }

            return retValue;
        }

        public byte[] GetState(string formName)
        {
            byte[] retValue = null;

            var obj = from x in context.FormsList
                      where x.FormName == formName
                      select x;

            if (obj.Any())
            {
                DAL.FormsList fconf = obj.FirstOrDefault();

                retValue = fconf.SerializedGridData;
            }

            return retValue;
        }

        public byte[] GetState(SavingConfigurationBag configuration)
        {
            byte[] retValue = null;

            if (configuration != null)
            {
                IQueryable<FormsList> query = context.FormsList.Where(x => x.FormName == configuration.FormName);

                if (!string.IsNullOrWhiteSpace(configuration.RoleName))
                {
                    query = query.Where(x => x.RoleName == configuration.RoleName);
                }

                if (!string.IsNullOrWhiteSpace(configuration.UserName))
                {
                    query = query.Where(x => x.UserName == configuration.UserName);
                }

                DAL.FormsList fconf = query.FirstOrDefault();
                if (fconf != null)
                {
                    retValue = fconf.SerializedGridData;
                }
            }

            return retValue;
        }
    }
}
